﻿using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using RotaractProjectCalendar.DataAccessLayer;
using RotaractProjectCalendar.ViewModels;

namespace RotaractProjectCalendar.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class ClubAccountController : Controller
    {
        private readonly CalendarContext _db = new CalendarContext();

        public ClubAccountController()
            : this(new UserManager<ClubAccount>(new UserStore<ClubAccount>(new CalendarContext())))
        {
        }

        private ClubAccountController(UserManager<ClubAccount> userManager)
        {
            UserManager = userManager;
        }

        private UserManager<ClubAccount> UserManager { get; set; }

        //
        // GET: /Admin/ClubAccount/RegisterNewClub
        public ActionResult RegisterNewClub()
        {
            var selectedClub = _db.Clubs
                                .OrderBy(club => club.ClubTitle)
                                .ToList();
            ViewBag.ClubId = new SelectList(_db.Clubs, "ID", "ClubTitle", selectedClub);

            return View();
        }

        //
        // POST: /Admin/ClubAccount/RegisterNewClub
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> RegisterNewClub(RegisterViewModel model)
        {
            if(ModelState.IsValid)
            {
                var user = new ClubAccount { UserName = model.UserName, ClubId = model.ClubId };
                var result = await UserManager.CreateAsync(user, model.Password);
                if(result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, "User");
                    return RedirectToAction("Index", "Club");
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            PopulateClubsDropdownLists();
            return View(model);
        }

        //
        // GET: /Admin/ClubAccount/Manage
        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : "";
            ViewBag.HasLocalPassword = HasPassword();
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        private void PopulateClubsDropdownLists()
        {
            ViewBag.ClubId = new SelectList(_db.Clubs, "ID", "Club Title", null);
        }

        //
        // POST: /Admin/ClubAccount/Manage
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Manage(ManageUserViewModel model)
        {
            var hasPassword = HasPassword();
            ViewBag.HasLocalPassword = hasPassword;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if(hasPassword)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }

                var result =
                    await
                        UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
                            model.NewPassword);
                if(result.Succeeded)
                {
                    return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                }

                AddErrors(result);
            }
            else
            {
                var state = ModelState["OldPassword"];
                if(state != null)
                {
                    state.Errors.Clear();
                }

                if(!ModelState.IsValid)
                {
                    return View(model);
                }

                var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
                if(result.Succeeded)
                {
                    return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                }

                AddErrors(result);
            }

            return View(model);
        }

        //
        // POST: /Admin/ClubAccount/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home", new { area="Anonymous" });
        }

        protected override void Dispose(bool disposing)
        {
            if(disposing && UserManager != null)
            {
                UserManager.Dispose();
                _db.Dispose();
                UserManager = null;
            }
            base.Dispose(disposing);
        }

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private void AddErrors(IdentityResult result)
        {
            foreach(var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }

        private bool HasPassword()
        {
            var user = UserManager.FindById(User.Identity.GetUserId());
            if(user != null)
            {
                return user.PasswordHash != null;
            }
            return false;
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            Error
        }
    }
}